package com.xyht.sca_s.student_manage_system.modules.student_subsidies.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.SmsStudentSubsidiesApply;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.SmsStudentSubsidiesFamilyRelation;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.SmsStudentSubsidiesTask;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.req.SmsStudentSubsidiesApplyReq;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.req.SmsStudentSubsidiesFamilyRelationReq;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesApplyResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesFamilyRelationResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesTaskApplyResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.entity.resp.SmsStudentSubsidiesTaskResp;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.mapper.SmsStudentSubsidiesApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.mapper.SmsStudentSubsidiesFamilyRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.mapper.SmsStudentSubsidiesTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.student_subsidies.service.SmsStudentSubsidiesApplyService;
import com.xyht.sca_s.student_manage_system.modules.tips.utils.TipsUtil;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.ApplyStatusConstant.APPLY_STATUS_REJECT;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.CloseFlagConstant.IS_CLOSE_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.CloseFlagConstant.IS_CLOSE_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.student_subsidies.constant.TaskRangeFlagConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.AppNameConstant.APP_BACK_SUBSIDIES;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.AppNameConstant.APP_WEB_SUBSIDIES;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.CommonConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.RangeTypeConstant.RANGE_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.TipsTypeConstant.TIPS_TYPE_MESSAGE;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.UserTypeConstant.USER_TYPE_STUDENT;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.UserTypeConstant.USER_TYPE_TEACHER;

/**
 * <p>
 * 国家助学金申请 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-02-26
 */
@Service
public class SmsStudentSubsidiesApplyServiceImpl extends ServiceImpl<SmsStudentSubsidiesApplyMapper, SmsStudentSubsidiesApply> implements SmsStudentSubsidiesApplyService {
    @Autowired
    private SmsStudentSubsidiesApplyMapper smsStudentSubsidiesApplyMapper;
    @Autowired
    private SmsStudentSubsidiesFamilyRelationMapper smsStudentSubsidiesFamilyRelationMapper;
    @Autowired
    private SmsStudentSubsidiesTaskMapper smsStudentSubsidiesTaskMapper;
    @Autowired
    private TipsUtil tipsUtil;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private SmsStudentSubsidiesApplyMapper smssubsidiesApplyMapper;
    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    @Autowired
    private SmsStudentInfoMapper smsStudentInfoMapper;

    @Override
    @Transactional
    public ResponseResult submitSubsidiesApply(SmsStudentSubsidiesApplyReq applyReq, String user_id) {
        if (isNullOrEmpty(applyReq.getTaskId()) || isNullOrEmpty(applyReq.getStuName())
                || isNullOrEmpty(applyReq.getStuNo()) || isNullOrEmpty(applyReq.getStuTel())
                || isNullOrEmpty(applyReq.getStuIdCard()) || isNullOrEmpty(applyReq.getStuSex())
                || isNullOrEmpty(applyReq.getStuBirth()) || isNullOrEmpty(applyReq.getStuCollege())
                || isNullOrEmpty(applyReq.getStuMajor()) || isNullOrEmpty(applyReq.getStuGrade())
                || isNullOrEmpty(applyReq.getStuClass()) || isNullOrEmpty(applyReq.getFamilyNum())
                || isNullOrEmpty(applyReq.getFamilyMonthIncome()) || isNullOrEmpty(applyReq.getFamilyMonthPerIncome())
                || isNullOrEmpty(applyReq.getFamilyIncomeSource()) || isNullOrEmpty(applyReq.getPostalCode())
                || isNullOrEmpty(applyReq.getFamilyAddr())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesTask task = smsStudentSubsidiesTaskMapper.selectById(applyReq.getTaskId());
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        //检查本人提交，避免重复提交
        List<SmsStudentSubsidiesApply> applyList = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, applyReq.getTaskId())
                .eq(SmsStudentSubsidiesApply::getUserId, user_id));
        if (applyList != null && applyList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_EXIST);
        }

        if (applyReq.getFamilyList() == null || applyReq.getFamilyList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_INVALID_FAMILY);
        }

        SmsStudentSubsidiesApply smsStudentSubsidiesApply = new SmsStudentSubsidiesApply();
        BeanUtils.copyProperties(applyReq, smsStudentSubsidiesApply);
        smsStudentSubsidiesApply.setUserId(user_id);

        smsStudentSubsidiesApplyMapper.insert(smsStudentSubsidiesApply);

        String apply_id = smsStudentSubsidiesApply.getId();
        if (isNullOrEmpty(apply_id)) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        for (SmsStudentSubsidiesFamilyRelationReq relationReq : applyReq.getFamilyList()) {
            if (isNullOrEmpty(relationReq.getAge()) || isNullOrEmpty(relationReq.getName())
                    || isNullOrEmpty(relationReq.getRelation()) || isNullOrEmpty(relationReq.getWorkAddr())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            SmsStudentSubsidiesFamilyRelation familyRelation = new SmsStudentSubsidiesFamilyRelation();
            BeanUtils.copyProperties(relationReq, familyRelation);

            familyRelation.setApplyId(apply_id);
            smsStudentSubsidiesFamilyRelationMapper.insert(familyRelation);
        }

        //完成消息待办
        tipsUtil.finishTips(applyReq.getTaskId(), user_id, null);

        //创建消息
        List<String> personList = new ArrayList<>();
        personList.add(task.getUserId());
        tipsUtil.addTips(TIPS_SUBSIDIES_TITLE_MESSAGE,
                TIPS_SUBSIDIES_TEACHER_DESCRIPTION_MESSAGE, //TIPS_LEAVE_DESCRIPTION_MESSAGE
                TIPS_TYPE_MESSAGE,
                APP_BACK_SUBSIDIES,
                RANGE_TYPE_PERSON, //RANGE_TYPE_ROLE
                personList.toString(),
                smsStudentSubsidiesApply.getId(),
                USER_TYPE_TEACHER,
                null
        );

        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult submitSubsidiesRejectApply(SmsStudentSubsidiesApplyReq applyReq, String user_id) {
        if (isNullOrEmpty(applyReq.getTaskId()) || isNullOrEmpty(applyReq.getStuName())
                || isNullOrEmpty(applyReq.getStuNo()) || isNullOrEmpty(applyReq.getStuTel())
                || isNullOrEmpty(applyReq.getStuIdCard()) || isNullOrEmpty(applyReq.getStuSex())
                || isNullOrEmpty(applyReq.getStuBirth()) || isNullOrEmpty(applyReq.getStuCollege())
                || isNullOrEmpty(applyReq.getStuMajor()) || isNullOrEmpty(applyReq.getStuGrade())
                || isNullOrEmpty(applyReq.getStuClass()) || isNullOrEmpty(applyReq.getFamilyNum())
                || isNullOrEmpty(applyReq.getFamilyMonthIncome()) || isNullOrEmpty(applyReq.getFamilyMonthPerIncome())
                || isNullOrEmpty(applyReq.getFamilyIncomeSource()) || isNullOrEmpty(applyReq.getPostalCode())
                || isNullOrEmpty(applyReq.getFamilyAddr()) || isNullOrEmpty(applyReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (applyReq.getFamilyList() == null || applyReq.getFamilyList().size() < 1) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_INVALID_FAMILY);
        }

        SmsStudentSubsidiesApply subsidiesApply = smsStudentSubsidiesApplyMapper.selectById(applyReq.getId());
        if (subsidiesApply == null || subsidiesApply.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_NOT_EXIST);
        }

        SmsStudentSubsidiesApply smsStudentSubsidiesApply = new SmsStudentSubsidiesApply();
        BeanUtils.copyProperties(applyReq, smsStudentSubsidiesApply);

        smsStudentSubsidiesApplyMapper.updateById(smsStudentSubsidiesApply);

        smsStudentSubsidiesFamilyRelationMapper.delete(new QueryWrapper<SmsStudentSubsidiesFamilyRelation>()
                .lambda().eq(SmsStudentSubsidiesFamilyRelation::getApplyId, applyReq.getId()));

        String apply_id = smsStudentSubsidiesApply.getId();
        if (isNullOrEmpty(apply_id)) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }

        for (SmsStudentSubsidiesFamilyRelationReq relationReq : applyReq.getFamilyList()) {
            if (isNullOrEmpty(relationReq.getAge()) || isNullOrEmpty(relationReq.getName())
                    || isNullOrEmpty(relationReq.getRelation()) || isNullOrEmpty(relationReq.getWorkAddr())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            SmsStudentSubsidiesFamilyRelation familyRelation = new SmsStudentSubsidiesFamilyRelation();
            BeanUtils.copyProperties(relationReq, familyRelation);

            familyRelation.setApplyId(apply_id);
            smsStudentSubsidiesFamilyRelationMapper.insert(familyRelation);
        }

        //完成消息待办
        tipsUtil.finishTips(apply_id, user_id, IS_CLOSE_TRUE);
        return CommonResult.success();
    }

    @Override
    public ResponseResult rejectSubsidiesApply(SmsStudentSubsidiesApplyReq applyReq) {
        if (isNullOrEmpty(applyReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesApply subsidiesApply = smsStudentSubsidiesApplyMapper.selectById(applyReq.getId());
        if (subsidiesApply == null || subsidiesApply.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_NOT_EXIST);
        }

        subsidiesApply.setApplyStatus(APPLY_STATUS_REJECT);
        subsidiesApply.setRejectInfo(applyReq.getRejectInfo());
        smsStudentSubsidiesApplyMapper.updateById(subsidiesApply);

        //创建消息
        List<String> personList = new ArrayList<>();
        personList.add(subsidiesApply.getUserId());
        tipsUtil.addTips(TIPS_SUBSIDIES_TITLE_MESSAGE,
                TIPS_SUBSIDIES_DESCRIPTION_MESSAGE, //TIPS_LEAVE_DESCRIPTION_MESSAGE
                TIPS_TYPE_MESSAGE,
                APP_WEB_SUBSIDIES,
                RANGE_TYPE_PERSON, //RANGE_TYPE_ROLE
                personList.toString(),
                subsidiesApply.getId(),
                USER_TYPE_STUDENT,
                null
        );
        return CommonResult.success();
    }

    @Override
    public ResponseResult getOwnSubsidiesTaskList(Integer pageNum, Integer pageSize, String user_id, String search_str) {
        List<SmsStudentSubsidiesApply> applyList = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getUserId, user_id));
        List<String> filledTaskList = applyList.stream().map(SmsStudentSubsidiesApply::getTaskId).collect(Collectors.toList());

        QueryWrapper<SmsStudentSubsidiesTask> queryWrapper = new QueryWrapper<>();
        if (filledTaskList.size() > 0) {
            queryWrapper.lambda().notIn(SmsStudentSubsidiesTask::getId, filledTaskList);
        }
        queryWrapper.lambda()
                .eq(SmsStudentSubsidiesTask::getIsClose, IS_CLOSE_FALSE)
                .and(smsStudentSubsidiesTaskLambdaQueryWrapper -> smsStudentSubsidiesTaskLambdaQueryWrapper.isNull(SmsStudentSubsidiesTask::getExpirationTime)
                        .or()
                        .gt(SmsStudentSubsidiesTask::getExpirationTime, new Date()))
                .orderByDesc(SmsStudentSubsidiesTask::getCreateTime);

        List<SmsStudentSubsidiesTask> taskList = smsStudentSubsidiesTaskMapper.selectList(queryWrapper);
        List<String> resultTaskIDList = taskList.stream().filter(task -> {
            List<String> rangeList = JSONObject.parseArray(task.getRangeId(), String.class);
            if (task.getTaskRange() != TASK_RANGE_ALL && (rangeList == null || rangeList.size() < 1)) {
                return false;
            }
            boolean flag = false;
            switch (task.getTaskRange()) {
                case TASK_RANGE_ALL:
                    flag = true;
                    break;
                case TASK_RANGE_ORG:
                    List<String> orgList = cacheUtil.getOrgList(user_id);
                    if (orgList != null && orgList.size() > 0) {
                        List<String> resultList = (List<String>) CollectionUtils.intersection(orgList, rangeList);
                        if (resultList.size() > 0) {
                            flag = true;
                        }
                    }
                    break;
                case TASK_RANGE_ROLE:
                    List<String> roleList = cacheUtil.getRoleList(user_id);
                    if (roleList != null && roleList.size() > 0) {
                        List<String> resultList = (List<String>) CollectionUtils.intersection(roleList, rangeList);
                        if (resultList.size() > 0) {
                            flag = true;
                        }
                    }
                    break;
                case TASK_RANGE_PERSON:
                    List<String> resultList = rangeList.stream().filter(person -> person.equals(user_id)).collect(Collectors.toList());
                    if (resultList.size() > 0) {
                        flag = true;
                    }
                    break;
            }
            return flag;
        }).map(SmsStudentSubsidiesTask::getId).collect(Collectors.toList());


        List<SmsStudentSubsidiesTaskResp> taskRespList = new ArrayList<>();
        int total = 0;
        if (resultTaskIDList.size() > 0) {
            Page<SmsStudentSubsidiesTask> page = new Page<>(pageNum, pageSize);
            QueryWrapper<SmsStudentSubsidiesTask> taskQueryWrapper = new QueryWrapper<>();
            if (!isNullOrEmpty(search_str)) {
                taskQueryWrapper.lambda().eq(SmsStudentSubsidiesTask::getTaskName, search_str);
            }
            taskQueryWrapper.lambda()
                    .in(SmsStudentSubsidiesTask::getId, resultTaskIDList);
            smsStudentSubsidiesTaskMapper.selectPage(page, taskQueryWrapper);
            taskRespList = page.getRecords().stream().map(task -> {
                SmsStudentSubsidiesTaskResp smsStudentSubsidiesTaskResp = new SmsStudentSubsidiesTaskResp();
                BeanUtils.copyProperties(task, smsStudentSubsidiesTaskResp);
                return smsStudentSubsidiesTaskResp;
            }).collect(Collectors.toList());
            total = (int) page.getTotal();

        }
        return CommonResult.success(taskRespList, total);
    }

    @Override
    public ResponseResult getSubmitSubsidiesApply(String task_id, String user_id) {
        SmsStudentSubsidiesApplyResp applyResp = new SmsStudentSubsidiesApplyResp();

        SmsStudentSubsidiesTask task = smsStudentSubsidiesTaskMapper.selectById(task_id);
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_NOT_EXIST);
        }

        List<SmsStudentSubsidiesApply> list = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getTaskId, task_id)
                .eq(SmsStudentSubsidiesApply::getUserId, user_id));
        if (list != null && list.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_EXIST);
        }

        SmsUser user = cacheUtil.getUserInfo(user_id);
        List<SmsStudentInfo> stuList = smsStudentInfoMapper.selectList(new QueryWrapper<SmsStudentInfo>()
                .lambda()
                .eq(SmsStudentInfo::getStuNo, user.getUsername()));
        if (stuList != null && stuList.size() > 0) {
            SmsStudentInfo smssubsidiesApply = stuList.get(0);
            BeanUtils.copyProperties(smssubsidiesApply, applyResp);
            applyResp.setId(null);
        }
        applyResp.setTaskId(task_id);
        return CommonResult.success(applyResp);
    }

    @Override
    public ResponseResult getSubsidiesApplyHistory(Integer pageNum, Integer pageSize, String user_id, String search_str) {
        List<SmsStudentSubsidiesApply> applyList = smsStudentSubsidiesApplyMapper.selectList(new QueryWrapper<SmsStudentSubsidiesApply>()
                .lambda()
                .eq(SmsStudentSubsidiesApply::getUserId, user_id));
        List<String> taskIDList = applyList.stream().map(SmsStudentSubsidiesApply::getTaskId).collect(Collectors.toList());

        List<SmsStudentSubsidiesTaskApplyResp> taskRespList = new ArrayList<>();
        int total = 0;
        if (taskIDList.size() > 0) {
            Page<SmsStudentSubsidiesTask> page = new Page<>(pageNum, pageSize);
            QueryWrapper<SmsStudentSubsidiesTask> queryWrapper = new QueryWrapper<>();
            if (!isNullOrEmpty(search_str)) {
                queryWrapper.lambda().eq(SmsStudentSubsidiesTask::getTaskName, search_str);
            }
            queryWrapper.lambda()
                    .in(SmsStudentSubsidiesTask::getId, taskIDList)
                    .orderByDesc(SmsStudentSubsidiesTask::getCreateTime);
            smsStudentSubsidiesTaskMapper.selectPage(page, queryWrapper);
            taskRespList = page.getRecords().stream().map(task -> {
                SmsStudentSubsidiesTaskApplyResp smsStudentSubsidiesTaskResp = new SmsStudentSubsidiesTaskApplyResp();
                BeanUtils.copyProperties(task, smsStudentSubsidiesTaskResp);

                List<SmsStudentSubsidiesApply> filterApply = applyList.stream()
                        .filter(apply -> apply.getTaskId().equals(task.getId()))
                        .collect(Collectors.toList());
                smsStudentSubsidiesTaskResp.setApplyStatus(filterApply.get(0).getApplyStatus());
                smsStudentSubsidiesTaskResp.setApply_id(filterApply.get(0).getId());
                smsStudentSubsidiesTaskResp.setRejectInfo(filterApply.get(0).getRejectInfo());
                return smsStudentSubsidiesTaskResp;
            }).collect(Collectors.toList());
            total = (int) page.getTotal();

        }
        return CommonResult.success(taskRespList, total);
    }

    @Override
    public ResponseResult getSubsidiesApplyDetail(String apply_id) {
        if (isNullOrEmpty(apply_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentSubsidiesApply subsidiesApply = smsStudentSubsidiesApplyMapper.selectById(apply_id);
        if (subsidiesApply == null || subsidiesApply.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_NOT_EXIST);
        }

        SmsStudentSubsidiesApplyResp applyResp = new SmsStudentSubsidiesApplyResp();
        BeanUtils.copyProperties(subsidiesApply, applyResp);

        List<SmsStudentSubsidiesFamilyRelationResp> familyRespList = smsStudentSubsidiesFamilyRelationMapper
                .selectList(new QueryWrapper<SmsStudentSubsidiesFamilyRelation>()
                        .lambda()
                        .eq(SmsStudentSubsidiesFamilyRelation::getApplyId, applyResp.getId()))
                .stream()
                .map(familyRelation -> {
                    SmsStudentSubsidiesFamilyRelationResp familyRelationResp = new SmsStudentSubsidiesFamilyRelationResp();
                    BeanUtils.copyProperties(familyRelation, familyRelationResp);
                    return familyRelationResp;
                })
                .collect(Collectors.toList());

        applyResp.setFamilyList(familyRespList);
        return CommonResult.success(applyResp);
    }

    @Override
    public ResponseResult exportSubsidiesApply(String apply_id, HttpServletResponse response) {
        try {
            SmsStudentSubsidiesApply subsidiesApply = smsStudentSubsidiesApplyMapper.selectById(apply_id);
            if (subsidiesApply == null || subsidiesApply.getId() == null) {
                return CommonResult.failed(CommonCodeEnum.SUBSIDIES_APPLY_NOT_EXIST);
            }

            List<SmsStudentSubsidiesFamilyRelation> familyRelationList = smsStudentSubsidiesFamilyRelationMapper.selectList(new QueryWrapper<SmsStudentSubsidiesFamilyRelation>()
                    .lambda()
                    .eq(SmsStudentSubsidiesFamilyRelation::getApplyId, apply_id));


            Map<String, Object> dataMap = new HashMap<>();
            //基础信息替换
            dataMap.put("stuName", getParamValue(subsidiesApply.getStuName()));
            dataMap.put("stuSex", getParamValue(subsidiesApply.getStuSex()));
            dataMap.put("stuBirth", getParamValue(subsidiesApply.getStuBirth()));
            dataMap.put("stuNation", getParamValue(subsidiesApply.getStuNation()));
            dataMap.put("stuPoliticCountenance", getParamValue(subsidiesApply.getStuPoliticCountenance()));
            dataMap.put("stuEnterTime", subsidiesApply.getStuEnterTime() == null ? " " : TimeUtil.DateSimpleformat(subsidiesApply.getStuEnterTime()));
            dataMap.put("stuNo", getParamValue(subsidiesApply.getStuNo()));
            dataMap.put("stuGrade", getParamValue(subsidiesApply.getStuGrade()));
            dataMap.put("stuIdCard", getParamValue(subsidiesApply.getStuIdCard()));
            dataMap.put("stuTel", getParamValue(subsidiesApply.getStuTel()));
            dataMap.put("stuCollege", getParamValue(subsidiesApply.getStuCollege()));
            dataMap.put("stuMajor", getParamValue(subsidiesApply.getStuMajor()));
            dataMap.put("stuClass", getParamValue(subsidiesApply.getStuClass()));
            dataMap.put("familyNum", getParamValue(subsidiesApply.getFamilyNum()));
            dataMap.put("familyMonthIncome", getParamValue(subsidiesApply.getFamilyMonthIncome()));
            dataMap.put("familyMonthPerIncome", getParamValue(subsidiesApply.getFamilyMonthPerIncome()));
            dataMap.put("familyIncomeSource", getParamValue(subsidiesApply.getFamilyIncomeSource()));
            dataMap.put("familyAddr", getParamValue(subsidiesApply.getFamilyAddr()));
            dataMap.put("postalCode", getParamValue(subsidiesApply.getPostalCode()));

            //家庭信息替换
            int count = 1;
            if (familyRelationList != null && familyRelationList.size() > 0) {
                for (SmsStudentSubsidiesFamilyRelation family : familyRelationList) {
                    dataMap.put("name" + count, family.getName() == null ? " " : family.getName());
                    dataMap.put("age" + count, family.getAge() == null ? " " : family.getAge());
                    dataMap.put("relation" + count, family.getRelation() == null ? " " : family.getRelation());
                    dataMap.put("workAddr" + count, family.getWorkAddr() == null ? " " : family.getWorkAddr());
                    count++;
                }
            }
            if (count < 6) {
                for (int i = count; i < 6; i++) {
                    dataMap.put("name" + i, " ");
                    dataMap.put("age" + i, " ");
                    dataMap.put("relation" + i, " ");
                    dataMap.put("workAddr" + i, " ");
                }
            }

//            dataMap.put("qrcode", QrUtil.crateQRCode("1234466", 100, 100));
            Configuration configuration = new Configuration(Configuration.getVersion());
            configuration.setDefaultEncoding("utf-8");
            String dd = "☑";
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("subsidies.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),
                    StandardCharsets.UTF_8), 10240);
            response.setHeader("file-type", "msw");
            response.setHeader("msw-name", URLEncoder.encode("国家助学金申请表_" + subsidiesApply.getStuName() + ".docx"));
//            response.setHeader("content-Type", "application/msword");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("国家助学金申请表_" + subsidiesApply.getStuName() + ".docx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,msw-name");
            response.flushBuffer();
            template.process(dataMap, out);
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
    }

    private Object getParamValue(Object value) {
        return value == null ? "" : value;
    }

}
